import { REQUEST_LOGIN, RECEIVE_LOGIN, 
    LOGOUT, FETCH_TODOLIST, POST_TODOLIST,
    NEWPROFILE
  } from '../constants/ActionTypes'
const initialState =
{
    username: '',
    first_name: '',
    last_name: '',
    isLogin: false,
    isLoggingIn: false,
    hasFetched: false,
    error: null
}
export default function userControl(state = initialState, action){
    switch(action.type){
        case REQUEST_LOGIN:
            return Object.assign({}, state, {
                isLoggingIn: true
            })
        case RECEIVE_LOGIN:
            if(action.error == null)
                return Object.assign({}, state, {
                    username: action.username,
                    isLogin: true,
                    isLoggingIn: false,
                    hasFetched: false,
                    error: null
                })
            return Object.assign({}, state, {
                username: '',
                isLogin: false,
                isLoggingIn: false,
                hasFetched: false,
                error: JSON.stringify(action.error)
            })
        case LOGOUT:
            if(action.error == null)
                return Object.assign({}, state, {
                    username: '',
                    isLogin: false,
                    error: null
                })
            else
                return Object.assign({}, state, {error: JSON.stringify(action.error)})
        case FETCH_TODOLIST:
            if(action.error != null)
                return Object.assign({}, state, {error: action.error})
            return Object.assign({}, state, {hasFetched: true, isLogin: true})
        case POST_TODOLIST:
            return Object.assign({}, state, {error: action.msg == null ? 'Save Successfully' : action.msg})
        case NEWPROFILE:
            if(action.error == null)
                return Object.assign({}, state, action.newProfile)
            return Object.assign({}, state, {error: JSON.stringify(action.error)})
        default:            
            return Object.assign({}, state, {error: null})
    }
}
